package com.recipedb.recipedb.controller;

import com.recipedb.recipedb.entity.Ingredient;
import com.recipedb.recipedb.entity.RecipeIngredient;
import com.recipedb.recipedb.service.RecipeIngredientService;
import com.recipedb.recipedb.service.IngredientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/api/ingredient")
public class IngredientController {

    @Autowired
    private IngredientService ingredientService;

    @Autowired
    private RecipeIngredientService recipeIngredientService;

    @PostMapping
    public Ingredient add(@RequestBody Ingredient entity) {
        return ingredientService.save(entity);
    }

    @DeleteMapping
    public void delete(@RequestParam Long id) {
        ingredientService.deleteById(id);
    }

    @GetMapping("/single")
    public Optional<Ingredient> get(@RequestParam Long id) {
        return ingredientService.findById(id);
    }

    @GetMapping("/all")
    public List<Ingredient> getAll() {
        return ingredientService.findAll();
    }

    @GetMapping("/by-recipe")
    public List<Map<String, Object>> getByRecipeId(@RequestParam Long recipeId) {
        Map<Ingredient, BigDecimal> ingredientMap = recipeIngredientService.findIngredientsByRecipeId(recipeId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (Map.Entry<Ingredient, BigDecimal> entry : ingredientMap.entrySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("ingredient", entry.getKey());
            map.put("amount", entry.getValue());
            result.add(map);
        }
        return result;
    }
}

